﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Caliburn.Micro;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace FuelTracker.Framework
{
    public class ValidationBase : PropertyChangedBase
    {
        private List<String> errors = new List<String>();

        public event EventHandler ValidStateChanged;

        public bool IsValid
        {
            get { return errors.Count == 0; }
        }

        public void AddError<TProperty>(Expression<Func<TProperty>> property)
        {
            string name = property.GetMemberInfo().Name;

            if (!errors.Contains(name))
            {
                errors.Add(name);
                NotifyIsValidChanged();
            }
        }

        public void ClearErrors<TProperty>(Expression<Func<TProperty>> property)
        {
             string name = property.GetMemberInfo().Name;
             errors.Remove(name);

             NotifyIsValidChanged();
        }

        public void ThrowIfError()
        {
            if (!IsValid)
                throw new Exception("ViewModel is not valid!");
        }

        private void NotifyIsValidChanged()
        {
            if (ValidStateChanged != null)
                ValidStateChanged(this, EventArgs.Empty);
        }
    }
}
